import {getToken, setToken, removeToken} from '@/utils/auth'
import {getCache, removeCache,setCache} from "@/utils/cache";
import {userLogin, logout, getInfo} from "@/api/user";
import {USER_INFO} from "@/utils/constants";

const state = {
  token: getToken(),
  userInfo: getCache(USER_INFO) || ""
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo;
    setCache(USER_INFO, userInfo);
  }
}

const actions = {
  login({commit}, userInfo) {
    const {code, key, password, username} = userInfo
    return new Promise((resolve, reject) => {
      userLogin({code, key, password, username}).then(response => {
        const {data} = response
        commit('SET_TOKEN', data.token);
        setToken(data.token);
        resolve();
      }).catch(error => {
        reject(error);
      })
    })
  },
  getInfo({commit, state}) {
    return new Promise((resolve, reject) => {
        getInfo(state.token).then(response => {
          const {data} = response
          if (!data) {
            reject('验证失败，请重新登录')
          } else {
            commit("SET_USERINFO", data);
            resolve()
          }
        })
      }
    )
  },
  logout({commit, state, dispatch}) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit("SET_TOKEN", '');
        removeToken();
        removeCache(USER_INFO);
        resolve();
      }).catch(error => {
        reject(error);
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
